
package com.wlsk.license.service.zpff;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.wlsk.license.common.constant.CharterConstantMsg;
import com.wlsk.license.common.utils.HttpUtils;
import com.wlsk.license.common.utils.PropertiesUtils;
import com.wlsk.license.common.utils.Sm4Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 获取报车牌接口公共类
 *
 * @author AmyOlive
 */
@Slf4j
public class CharterApplyLicense {

    public static final String CHARTER_APPLY_DOMAIN;

    static {
        CHARTER_APPLY_DOMAIN = PropertiesUtils.get("charter.apply.domain").trim();
        log.info("报车牌接口域名：{}", CHARTER_APPLY_DOMAIN);
    }

    public static final Object LOCK = new Object();

    // 用户登录获取token
    public static final String login = CHARTER_APPLY_DOMAIN + "outInterface/login.interface";

    // 获取业户信息
    public static final String GET_OWNER_INFO = CHARTER_APPLY_DOMAIN + "outInterface/getOwnerInfo.interface";

    // 反馈业户信息-新接口
    public static final String REBACK_OWNER_INFO = CHARTER_APPLY_DOMAIN + "outOwnerInterface/rebackOwnerInfo.interface";

    // 提交运次信息
    public static final String REBACK_YCINFO = CHARTER_APPLY_DOMAIN + "outInterface/rebackYcInfo.interface";

    // 申请车辆信息接口
    public static final String GET_VEHCILEINFO_URL = CHARTER_APPLY_DOMAIN + "outInterface/getVehicleInfo.interface";

    // 反馈车辆信息接口
    public static final String SUBMIT_VEHICLE_URL = CHARTER_APPLY_DOMAIN + "outInterface/rebackVehicleInfo.interface";

    // 申请驾驶员信息接口
    public static final String GET_DRIVERINFO_URL = CHARTER_APPLY_DOMAIN + "outInterface/getDriverInfo.interface";

    // 反馈驾驶员信息接口
    public static final String SUBMIT_DRIVER_URL = CHARTER_APPLY_DOMAIN + "outInterface/rebackDriverInfo.interface";

    // 获取行政区划
    public static final String GET_CITIESDJ = CHARTER_APPLY_DOMAIN + "outInterface/getCitiesDj.interface";

    // 附件上传
    public static final String UPLOAD_FILE_INFO = CHARTER_APPLY_DOMAIN + "outInterface/uploadFileAndStore.interface";

    // 运管提交信息
    public static final String MTASAVE_DRAFT = CHARTER_APPLY_DOMAIN + "outInterface/saveApply.interface";

    // 签发/审核
    public static final String SAVE_ISSUE_OR_APPROVE = CHARTER_APPLY_DOMAIN + "outInterface/saveIssueOrApprove.interface";

    // 归档
    public static final String UPDATE_BCP_ARCHIVEDLIST = CHARTER_APPLY_DOMAIN + "outInterface/updateBcpArchivedList.interface";

    // 作废
    public static final String GET_CANCEL = CHARTER_APPLY_DOMAIN + "outInterface/getCancel.interface";

    // 运管删除草稿
    public static final String MTA_DELETE_DRAFT = CHARTER_APPLY_DOMAIN + "outInterface/deleteDraft.interface";

    // 删除驾驶员信息接口
    public static final String DELETE_DRIVER_URL = CHARTER_APPLY_DOMAIN + "outInterface/deleteAppDriverInfo.interface";

    // 审核后终止
    public static final String TO_EXAMINERMINATION = CHARTER_APPLY_DOMAIN + "outInterface/saveFfbc002Invid.interface";

    // 作废后终止
    public static final String TO_VOIDMINATION = CHARTER_APPLY_DOMAIN + "outInterface/saveFfbc002End.interface";

    // 申请电子包车牌
    public static final String APPLY_ELECTRONIC_LICPLA_URL = CHARTER_APPLY_DOMAIN + "outInterface/generateElectronCharter.interface";

    // 回传已签章的电子包车牌
    public static final String REBACK_ELECTRONIC_LICPLA_URL = CHARTER_APPLY_DOMAIN + "outInterface/uploadElectronCharterFile.interface";

    // 电子包车牌下载地址
    public static final String ATTACHMENT_DOWNLOAD_URL_STRING = CHARTER_APPLY_DOMAIN + "outInterface/downloadFile.interface";

    // 打印结果反馈接口
    public static final String FEEDBACK_PRINT_INFORMATION = CHARTER_APPLY_DOMAIN + "outInterface/printCharterlic.interface";

    // 查询公司办理了多少包车牌
    public static final String QUERY_HANDLING_SITUATION = CHARTER_APPLY_DOMAIN + "outInterface/QueryHandlingSituation.interface";

    // 车辆和驾驶员状态查询(是否在流程中)
    public static final String SELECT_IS_PROCESS = CHARTER_APPLY_DOMAIN + "outInterface/selectIsProcess.interface";

    // 根据申请编号查询包车系统状态
    public static final String MTA_SYS_STATUS = CHARTER_APPLY_DOMAIN + "outInterface/selectState.interface";

    // 待审核终止
    public static final String TO_WAITCHECKMINATION = CHARTER_APPLY_DOMAIN + "outInterface/signInvid.interface";
    //直接终止
    public static final String DIRECT_TO_WAITCHECKMINATION = CHARTER_APPLY_DOMAIN + "outInterface/endBcp.interface";

    // 开启日志记录
    public static final boolean LOG_ON = true;

    // 任务状态常量(BPM流程参数-任务状态常量)
    public static final HashMap<String, String> TASK_STATUS_CONSTANT = new HashMap<String, String>();

    // 包车牌状态
    public static final HashMap<Integer, String> LICPLA_STATUS_CONSTANT = new HashMap<Integer, String>();

    private static final Logger LOGGER = LoggerFactory.getLogger(CharterApplyLicense.class);

    static {
        // 初始化BPM流程参数-任务状态常量数据
        TASK_STATUS_CONSTANT.put("91190001", "提交");
        TASK_STATUS_CONSTANT.put("91190005", "打回重填");
        TASK_STATUS_CONSTANT.put("91190002", "取消流程");
        TASK_STATUS_CONSTANT.put("91190004", "终止");
        TASK_STATUS_CONSTANT.put("91190003", "同意");

        // 初始化包车牌状态常量
        LICPLA_STATUS_CONSTANT.put(1001, "未审核");
        LICPLA_STATUS_CONSTANT.put(1002, "已审核未打印");
        LICPLA_STATUS_CONSTANT.put(1003, "已打印");
        LICPLA_STATUS_CONSTANT.put(1005, "打回重填");
        LICPLA_STATUS_CONSTANT.put(1006, "已归档");
        LICPLA_STATUS_CONSTANT.put(1007, "草稿");
        LICPLA_STATUS_CONSTANT.put(1008, "待签发");
        LICPLA_STATUS_CONSTANT.put(1009, "已终止");
        LICPLA_STATUS_CONSTANT.put(1010, "外省包车");
        LICPLA_STATUS_CONSTANT.put(1012, "作废重打");
        LICPLA_STATUS_CONSTANT.put(1016, "已生成电子包车牌");
    }

    /**
     * 请求获取返回数据(加/解密数据)
     */
    public static Map<String, String> gainCharterLicenseData(String reqBodyJson, String url) {
        String body = null;
        try {
            // sm4加密
            body = Sm4Util.encryptEcb(RtabTokenHelper.KEY, reqBodyJson);
        } catch (Exception e) {
            log.error("sm4加密异常:{}-{}",RtabTokenHelper.KEY, reqBodyJson, e);
        }
        int i = 0;
        String resultNode;
        do {
            try {
                String token = RtabTokenHelper.getToken();
                JSONObject jsonParam = new JSONObject();
                jsonParam.put("username", RtabTokenHelper.USERNAME);
                jsonParam.put("token", token);
                jsonParam.put("body", body);
                String jsonParamStr = JSONObject.toJSONString(jsonParam);
                resultNode = HttpUtils.sendTextPost(url, jsonParamStr);
                RtabResult result = RtabHelper.handleResponse(resultNode);
                if (result.getResultCode() == RtabResultCode.TOKEN_ERROR) {
                    RtabTokenHelper.updateToken(token);
                    i++;
                    continue;
                }
                break;
            } catch (IOException e) {
                log.error("An error occurred accessing the rtab-interface. ", e);
                resultNode = "运管接口访问错误";
            }
        } while (i < 3);
        Map<String, String> result = receiveCharterLicenseData(RtabTokenHelper.KEY, resultNode);
        JSONObject reqJson = JSONObject.parseObject(reqBodyJson);
        if (reqJson != null && reqJson.containsKey("base64Content")) {
            log.info("removeBase64======>");
            reqJson.remove("base64Content");
            log.info("ele-charter===>:{}", reqJson);
        }
        // 存入日志记录
        if (LOG_ON) {

        }
        return result;
    }

    /**
     * 请求获取返回数据(加/解密数据)
     */
    public static <T> T requestCharterLicenseData(Object reqDto, String url, Class<T> clazz) {
        String body = null;
        try {
            // sm4加密
            body = Sm4Util.encryptEcb(RtabTokenHelper.KEY, JSONObject.toJSONString(reqDto));
        } catch (Exception e) {

        }
        int i = 0;
        String resultNode;
        do {
            try {
                String token = RtabTokenHelper.getToken();
                JSONObject jsonParam = new JSONObject();
                jsonParam.put("username", RtabTokenHelper.USERNAME);
                jsonParam.put("token", token);
                jsonParam.put("body", body);
                String jsonParamStr = JSONObject.toJSONString(jsonParam);
                resultNode = HttpUtils.sendTextPost(url, jsonParamStr);
                RtabResult result = RtabHelper.handleResponse(resultNode);
                if (result.getResultCode() == RtabResultCode.TOKEN_ERROR) {
                    RtabTokenHelper.updateToken(token);
                    i++;
                    continue;
                }
                break;
            } catch (IOException e) {
                log.error("An error occurred accessing the rtab-interface. ", e);
                resultNode = "运管接口访问错误";
            }
        } while (i < 3);
        Map<String, String> result = receiveCharterLicenseData(RtabTokenHelper.KEY, resultNode);
        JSONObject reqJson = JSONObject.parseObject(JSONObject.toJSONString(reqDto));
        if (reqJson != null && reqJson.containsKey("base64Content")) {
            log.info("removeBase64======>");
            reqJson.remove("base64Content");
            log.info("ele-charter===>:{}", reqJson);
        }
        if(result.containsKey("data")){
            return JSONObject.parseObject(result.get("data"), clazz);
        }
        return null;
    }

    /**
     * 解密数据
     */
    public static Map<String, String> receiveCharterLicenseData(String key, String resultNode) {

        // 将参数格式化json格式
        JSONObject jsonObject = JSONObject.parseObject(resultNode);
        // 获取指定参数
        String body = jsonObject.getString("data");
        String code = jsonObject.getString("code");
        String desc = jsonObject.getString("desc");
        try {
            // ===验证请求报文===
            if (code.equals("200")) {
                // 解密
                body = Sm4Util.decryptEcb(key, body);
            } else {
                // 先循环错误提示信息
                Map<String, String> errorMsgMap = CharterConstantMsg.getErrorMsgMap();
                if (errorMsgMap.containsKey(desc)) {
                    body = "包车系统返回:" + errorMsgMap.get(desc);
                } else {
                    if (StringUtils.isNotEmpty(desc) && desc.contains("exceptions")) {
                        body = "包车系统返回:系统出错，请联系系统管理员！";
                    } else if (StringUtils.isNotEmpty(desc) && desc.contains("Unparseable")) {
                        body = "包车系统返回:系统出错，数据解析异常！";
                    } else if (StringUtils.isNotEmpty(desc) && desc.contains("Exception")) {
                        body = "包车系统返回:系统出错，数据处理异常！";
                    } else {
                        body = "包车系统返回:" + desc;
                    }
                }
            }

        } catch (Exception e) {
            LOGGER.error("业户信息请求异常", e);
        }

        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("code", code);
        paramMap.put("desc", desc);
        paramMap.put("data", body);
        return paramMap;
    }

    public static void main(String[] args) throws JsonProcessingException {
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("liceno", "500223990053");
        String jsonParamStr = JSONObject.toJSONString(jsonParam);
        Map<String, String> map = CharterApplyLicense.gainCharterLicenseData(jsonParamStr,
                CharterApplyLicense.GET_OWNER_INFO);
        String body = "";
        for (String key : map.keySet()) {
            if (key.equals("data")) {
                body = map.get("data");
            }
        }
//        Map<String, Object> map2 = new ObjectMapper().readValue(map.get("data"), Map.class);



        System.out.println(map);
    }
}
